package com.example.chatplatform.service.impl;

import com.example.chatplatform.mapper.CronyMapper;
import com.example.chatplatform.model.dto.AddCronyDTO;
import com.example.chatplatform.model.vo.CronyInformVO;
import com.example.chatplatform.service.CronyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class CronyServiceImpl implements CronyService {

    @Autowired
    public CronyMapper cronyMapper;

    @Override
    public boolean isCrony(Integer userId, Integer cronyId) {
        Integer i1 = cronyMapper.isCrony1(userId, cronyId);
        Integer i2 = cronyMapper.isCrony2(userId, cronyId);
        if (i1 != null && i1 > 0) {
            return true;
        } else {
            if (i2 != null) {
                if (i2 == 0 || i2 == 1) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    }

    @Override
    public boolean addCrony(AddCronyDTO addCrony) {
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 定义日期和时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前日期和时间为字符串
        String formattedDateTime = currentDateTime.format(formatter);

        addCrony.setFoundTime(formattedDateTime);
        addCrony.setFoundStatus(0);
        if (cronyMapper.foundCrony(addCrony) != null) {
            return cronyMapper.updateCrony(addCrony) > 0;
        } else {
            return cronyMapper.addCrony(addCrony) > 0;
        }
    }

    @Override
    public boolean agreeCrony(Integer cronyId, Integer userId) {
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 定义日期和时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前日期和时间为字符串
        String formattedDateTime = currentDateTime.format(formatter);
        Integer i1 = cronyMapper.agreeCrony(cronyId, userId);
        Integer i2 = cronyMapper.addUserCrony(cronyId, userId, formattedDateTime);
        return i1 > 0 && i2 > 0;
    }

    @Override
    public boolean refusalCrony(Integer cronyId, Integer userId) {
        return cronyMapper.refusalCrony(cronyId, userId) > 0;
    }

    @Override
    public List<CronyInformVO> getCronyInform(Integer userId) {
        return cronyMapper.getCronyInform(userId);
    }

    @Override
    public boolean deleteCrony(Integer userId, Integer cronyId) {
        return cronyMapper.deleteCrony(userId, cronyId) > 0 &&
                cronyMapper.deleteCronyMessage(userId, cronyId) > 0 &&
                cronyMapper.deleteFoundCrony(userId, cronyId) > 0;
    }
}
